#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWebFrame>
#include <QWebElement>
#include <QMessageBox>
#include <QStringListModel>
#include "datafrome.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_configSet.readSet();
    if(!DocumentDate::openSql()){
        QMessageBox::information(this,"error","打开数据库异常");
    }

    connect(this,SIGNAL(toChangeUrl(QString)),this,SLOT(on_toChangerUrl(QString)));
    connect(this,SIGNAL(toChanegeGetUrlEnd()),this,SLOT(on_toChangerGetUrlEnd()));

    //get doc
    webView = new QWebView();
    connect(webView,SIGNAL(loadFinished(bool)),this,SLOT(on_webView_loadFinished()));

    //get url
    m_configSetItemIt = m_configSet.m_ItemList.begin();
    if(m_configSetItemIt != m_configSet.m_ItemList.end()){
        m_hostUrl = (*m_configSetItemIt).host;
        webView_url = new QWebView();
        connect(webView_url,SIGNAL(loadFinished(bool)),this,SLOT(on_webView_loadFinished_geturl()));
        qDebug()<<(*m_configSetItemIt).hostUrl;
//        webView_url->setHtml( getHtml((*m_configSetItemIt).hostUrl));
        webView_url->setUrl(QUrl((*m_configSetItemIt).hostUrl));
    }
    loadDataToListView();
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::getHtml(QString url)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
    QByteArray responseData;
    QEventLoop eventLoop;
    connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    eventLoop.exec();       //block until finish
    responseData = reply->readAll();
    return QString(responseData);
}

void MainWindow::on_webView_loadFinished()
{
        QWebFrame *frame =  webView->page()->mainFrame();
        QWebElement element_title = frame->findFirstElement((*m_urlListIt).configItem.titleIdOrClassStr);
        QWebElement element_content = frame->findFirstElement((*m_urlListIt).configItem.contentIdOrClassStr);
        DocumentDate doc ;
        doc.url = webView->page()->mainFrame()->url().toString();
        doc.title = element_title.toPlainText();
        doc.content = element_content.toPlainText();
        addDoucment(doc);
        m_urlListIt++;
        if(m_urlListIt != m_urlList.end()){
            emit toChangeUrl((*m_urlListIt).url);
        }else{
            qDebug()<<"list end";
            loadDataToListView();
//            emit toChanegeUrlEnd();
        }

}

void MainWindow::on_webView_loadFinished_geturl()
{
    QWebFrame *frame = webView_url->page()->mainFrame();
    QWebElementCollection element1 = frame->findAllElements((*m_configSetItemIt).urlIdOrClassStr);
    qDebug()<<frame->toHtml();
    for(int i=0 ;i<element1.count();i++){
        QRegExp rx((*m_configSetItemIt).urlRegexpStr);
        rx.setCaseSensitivity(Qt::CaseInsensitive);
        rx.setMinimal(true);
//        qDebug()<<element1[i].toInnerXml();
        int pos = element1[i].toInnerXml().indexOf(rx);
        while ((pos = rx.indexIn(element1[i].toInnerXml(), pos)) != -1) {
             pos += rx.matchedLength();
             addUrl(rx.capturedTexts()[1],m_hostUrl,(*m_configSetItemIt));
        }
    }
    m_configSetItemIt++;
    if(m_configSetItemIt != m_configSet.m_ItemList.end()){
        emit toChanegeGetUrlEnd();
    }else{
        finshedAddUrl();
    }
}

void MainWindow::on_toChangerUrl(QString url)
{
    qDebug()<<"on_toChanerUrl:"<<url;
    webView->setUrl(QUrl(url));
}

void MainWindow::on_toChangerGetUrlEnd()
{
    qDebug()<<"on_toChangerUrlEnd";
    qDebug()<<(*m_configSetItemIt).hostUrl;
    webView_url->setHtml( getHtml((*m_configSetItemIt).hostUrl));
}

void MainWindow::addUrl(QString pathUrl, QString hostUrl, ConfigSetItem configItem)
{
    QString strUrl ="";
    if(hostUrl.length()==0){
        strUrl = pathUrl;
    }else {
        strUrl = hostUrl+pathUrl;
    }
    //fix the all url;
    if(DocumentDate::isExistedData(strUrl)){
        qDebug()<<"data is existed!";
        return;
    }
    qDebug()<<"addUrl:"<<strUrl;
    UrlData data;
    data.url = strUrl;
    data.configItem = configItem;
    m_urlList.push_back(data);
}

void MainWindow::addDoucment(DocumentDate doc)
{
//    qDebug()<<doc.url;
//    qDebug()<<doc.title;
//    qDebug()<<doc.content;
    if(DocumentDate::isExistedData(doc.url)){
        qDebug()<<"data is existed!";
        return;
    }
    if(doc.insertData()){
        qDebug()<<"insertData ok";
    }else{
        qDebug()<<"insertData fail";
    }
//    m_docList.push_back(doc);
}

void MainWindow::finshedAddUrl()
{
    if(m_urlList.isEmpty()){
        return;
    }
    qDebug()<<"finshedAddUrl:"<<m_urlList.first().url;
    m_urlListIt = m_urlList.begin();
    emit toChangeUrl((*m_urlListIt).url);
//    if(m_urlListIt != m_urlList.end()){
//        m_urlListIt++;
//    }
}

void MainWindow::loadDataToListView()
{
    QStringList list;
    QList<DocumentDate> *listData = DocumentDate::loadDataFromDatabase();
    if(listData != NULL){
        for(QList<DocumentDate>::iterator it = listData->begin();
            it != listData->end();it++){
            list<<(*it).title;
        }

        QStringListModel *listMode =  new QStringListModel(list);
        ui->listView->setModel(listMode);
    }
}

void MainWindow::loadDataToListView(QList<DocumentDate> docList)
{
    QStringList list;
//    if(docList.length() != 0){
        for(QList<DocumentDate>::iterator it = docList.begin();
            it != docList.end();it++){
            list<<(*it).title;
        }

        QStringListModel *listMode =  new QStringListModel(list);
        ui->listView->setModel(listMode);
//    }
}


void MainWindow::on_listView_doubleClicked(const QModelIndex &index)
{
    QString url = index.data().toString();
    QList<DocumentDate> data = DocumentDate::getData(url);
    if(!data.isEmpty()){
        DataFrome *frame = new DataFrome(0,data.first());
        frame->show();
    }
}

void MainWindow::on_search_btn_clicked()
{

    loadDataToListView(DocumentDate::getData(ui->lineEdit->text(),""));
}

void MainWindow::on_lineEdit_returnPressed()
{
    on_search_btn_clicked();
}
